package xfuzzy.alg_genetico.indeterminado.evaluation;

import java.util.List;

import xfuzzy.xfghl.algorithm.ResultGA;
import xfuzzy.xfghl.codification.DoubleChromosome;
import xfuzzy.xfghl.evaluation.XfghlThread;
import xfuzzy.xfghl.model.XfghlConfig;
import xfuzzy.xfhl.model.XfhlData;

public class XfghlProcessNew {

	public static int MODE_POPULATION = 1;
	public static int MODE_OFFSPRING = 2;
	private int mode;
	
	/**
	 * Configuracion de la herramienta Xfhl
	 */
	private XfghlConfig xfghlConf;
	//private XfghlThreadNew [] threads;
	
	public XfghlProcessNew(XfghlConfig config)  {
		
		this.mode = -1;
		//this.threads = new XfghlThreadNew[config.getNumThread()];
		this.xfghlConf = config;
	}
	
	public XfghlProcessNew(int mode)  {
		
		this.mode = mode;
	}
	
	public void execute(XfghlConfig config, List<DoubleChromosome> chromosomes, ResultGA result)  {
		
		int nthreads = 0;
		Thread [] threads = null;
		// no se ha contemplado la posibilidad de que existan mas hilos que individuos en la poblacion
		// se debe controlar en la interfaz que la poblacion minima sea de 30, la maxima en principio
		// seria de 60
		
		if (this.mode == MODE_POPULATION)  {
			int indexThread = 0;
			nthreads = config.getNumThread();
			//System.out.println("Threads = " + config.getNumThread());
			System.out.println("Modo poblacion");
			threads = new Thread[config.getNumThread()];
			XfghlThread [] xfghlthreads = new XfghlThread[config.getNumThread()];
			for (int i = 0; i < config.getNumThread(); i++)
				 xfghlthreads[i] = new XfghlThread(config, new XfhlData(i, config.getnumIterAjust()));
			
			for (DoubleChromosome chromosome : chromosomes)  {
				 xfghlthreads[indexThread].addChromosome(chromosome);
				 indexThread = (indexThread + 1) % config.getNumThread();
			}
			System.out.println("Inicio ejecucion poblacion");
			for (int i = 0; i < config.getNumThread(); i++)  {
				threads[i] = new Thread(xfghlthreads[i]);
				threads[i].start();
			}
				
		}
		else if (this.mode == MODE_OFFSPRING)  {
			System.out.println("Modo nueva generacion");
			nthreads = 2;
			XfghlThread [] xfghlthreads = new XfghlThread[2];
			threads = new Thread[2];
			XfhlData data1 = new XfhlData(0, config.getnumIterAjust());
			XfhlData data2 = new XfhlData(1, config.getnumIterAjust());
			xfghlthreads[0] = new XfghlThread(config, data1, chromosomes.get(0), null);
			xfghlthreads[1] = new XfghlThread(config, data2, chromosomes.get(1), null);
			threads[0] = new Thread(xfghlthreads[0]);
			threads[1] = new Thread(xfghlthreads[1]);
			System.out.println("Inicio ejecucion nueva generacion");
			for (int i = 0; i < 2; i++)  {
				 threads[i].start();
			}
		}
		
		for (int i = 0; i < nthreads; i++)  {
			try {
				threads[i].join();
			} 
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * @return Devuelve la configuracion de la herramienta Xfhl
	 */
	public XfghlConfig getConfig() {
		return this.xfghlConf;
	}
}
